import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { verify } from 'argon2';
import { BaseService } from 'src/base/base.service';
import { CreateAdminuserDto } from './dto/create-adminuser.dto';
import { LoginAdminUserDto } from './dto/login-adminuser.dto';
import { UpdateAdminuserDto } from './dto/update-adminuser.dto';
import { adminUser } from '@prisma/client'

@Injectable()
export class AdminuserService {
  constructor(private baseService: BaseService, private jwt: JwtService) {}

  create(createAdminuserDto: CreateAdminuserDto) {
    return 'This action adds a new adminuser';
  }

  findAll() {
    return `This action returns all adminuser`;
  }


  update(id: number, updateAdminuserDto: UpdateAdminuserDto) {
    return `This action updates a #${id} adminuser`;
  }


  async adminLogin(dto: LoginAdminUserDto) {
    console.log(dto);
    const user = await this.baseService.adminUser.findUnique({
      where: {
        userName: dto.userName
      }
    })
    if(!await (verify( user.password, dto.password))) {
      throw new BadRequestException('密码错误')
    }

    return await this.token(user)
  }

  private async token(argUser: adminUser) {
    const {userName, id} = argUser
    const user = {
      id,
      userName
    }
    return {
      user,
      token: await this.jwt.signAsync({
        userName,
        sub: id
      })
    }
  }
}
